<?php
namespace com\rs\dns\controller\api;

use com\rs\dns\constant\UserConstant;
use com\rs\dns\constant\UserSessionErrorConstant;
use com\rs\dns\controller\api\vo\UserModify;
use com\rs\dns\controller\api\vo\UserRegister;
use com\rs\dns\controller\BaseController;
use com\rs\dns\exception\BaException;
use com\rs\dns\service\MemberRandCodeService;
use com\rs\dns\service\user\impl\UserManageServiceImpl;
use com\rs\dns\service\user\impl\UserServiceImpl;
use restphp\http\RestHttpRequest;
use restphp\utils\RestClassUtils;
use restphp\validate\RestValidate;

/**
 * Class UserController
 * @package classes\controller\api
 * @RequestMapping("/api/users")
 */
final class UserController extends BaseController {
    /**
     * 用户注册.
     * @RequestMapping(value="", method="POST")
     * @throws \ReflectionException|BaException
     * @throws \restphp\exception\RestException
     */
    public function userRegister() {
        $user = RestHttpRequest::getRequestBody(new UserRegister());
        RestValidate::execute($user);

        // 验证码校查
        if (!MemberRandCodeService::checkCode($user->getRandCode())) {
            throw new BaException(UserSessionErrorConstant::USER_LOGIN_RAND_CODE_ERROR);
        }

        $arrRegister = RestClassUtils::beanToArr($user);
        $arrRegister['tel'] = $arrRegister['mobile'];
        $arrRegister['password'] = $arrRegister['passwd'];
        $arrRegister['username'] = $arrRegister['account'];
        unset($arrRegister['randCode']);
        unset($arrRegister['mobile']);
        unset($arrRegister['passwd']);
        unset($arrRegister['account']);
        $arrRegister['isadmin'] = UserConstant::DEF_IS_ADMIN;
        $arrRegister['soanum'] = UserConstant::DEF_SOA_NUM;
        $arrRegister['rrnum'] = UserConstant::DEF_RR_NUM;
        $arrRegister['verify'] = 'N';

        $userManageService = new UserManageServiceImpl();
        $userManageService->addUser($arrRegister);
    }

    /**
     * 获取个人信息.
     * @RequestMapping(value="/_self", method="GET")
     */
    public function _selfInfo() {
        $userService = new UserServiceImpl();
        $userInfo = $userService->getInfo($this->_userSession->getSession()->getID());
        $userInfo->setPassword('');
        $this->_success($userInfo);
    }

    /**
     * 修改个人信息.
     * @RequestMapping(value="/_self", method="PUT")
     * @throws \ReflectionException
     * @throws \restphp\exception\RestException
     */
    public function _selfModify() {
        $userInfo = RestHttpRequest::getRequestBody(new UserModify(), true);
        $arrUpdate = RestClassUtils::beanToArr($userInfo);
        $userId = $this->_userSession->getSession()->getID();

        $userService = new UserServiceImpl();
        $userService->modify($userId, $arrUpdate);
    }
}